package itsm.isperp.framework.web.converter;

import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.converter.Converter;

/**
 * 
 * 
 * @author lizx
 * @date 2013-5-27
 */
public class SqlTimeConverter implements Converter<String, Time> {

	public static final DateFormat TF_LONG = new SimpleDateFormat("HH:mm:ss");
	public static final DateFormat TF_SHORT = new SimpleDateFormat("HH:mm");

	public static int SHORT_TIME = 5;

	@Override
	public Time convert(String source) {

		source = source.trim();
		if (StringUtils.isEmpty(source)) {
			return null;
		}
		try {
			if (source.length() <= SHORT_TIME) {
				return new java.sql.Time(TF_SHORT.parse(source).getTime());
			} else {
				return new java.sql.Time(TF_LONG.parse(source).getTime());
			}
		} catch (ParseException ex) {
			IllegalArgumentException iae = new IllegalArgumentException(
					"Could not parse date: " + ex.getMessage());
			iae.initCause(ex);
			throw iae;
		}
	}

}
